package Administracion;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;
import com.mysql.jdbc.ResultSetMetaData;
import java.awt.Component;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URL;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import static javax.swing.JFileChooser.SAVE_DIALOG;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRExporter;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.export.JRPdfExporter;
import net.sf.jasperreports.engine.util.JRLoader;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 *
 * @author pato
 */
public class ventasdia extends javax.swing.JInternalFrame {

    local_connection conexion;
    Connection cn;
    PreparedStatement ps;
    ResultSet rs;
    NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.getDefault());
    String fI = "", fF = "", hI, hF;
    DefaultTableModel dtm;
    ResultSetMetaData rsm;

    /**
     * Creates new form ventasdia
     */
    public ventasdia() {
        initComponents();
        jSpinField1.setMaximum(23);
        jSpinField1.setMinimum(0);
        jSpinField2.setMaximum(59);
        jSpinField2.setMinimum(0);
        jSpinField3.setMaximum(59);
        jSpinField3.setMinimum(0);
        jSpinField4.setMaximum(23);
        jSpinField4.setMinimum(0);
        jSpinField5.setMaximum(59);
        jSpinField5.setMinimum(0);
        jSpinField6.setMaximum(59);
        jSpinField6.setMinimum(0);
        todo.setSelected(true);
        dtm = (DefaultTableModel) this.jTable1.getModel();
        TableRowSorter<TableModel> elQueOrdena = new TableRowSorter<TableModel>(dtm);
        jTable1.setRowSorter(elQueOrdena);
        cargarDatos();
    }

    private void cargarDatos() {

        dtm.setRowCount(0);
        String tipo = "";
        try {
            if (cursos.isSelected()) {
                tipo = "productos.tipo = 'Curso' and";
            }
            if (productos.isSelected()) {
                tipo = "productos.tipo = 'Producto' and";
            }
            cn = local_connection.getconnect();
            ps = (PreparedStatement) cn.prepareStatement("select productos.id_producto, IF(productos.id_producto!=-2,nombre,(select nombre from otros where detalle_venta = idetalle)) AS nombre, sum(cantidad),sum(cantidad*detalleventa.preciocompra) ,\n"
                    + "sum(cantidad*preciovendido), sum(cantidad*(preciovendido-detalleventa.preciocompra))\n"
                    + " from detalleventa join venta on detalleventa.folio=venta.folio\n"
                    + "join productos on productos.id_producto=detalleventa.id_producto\n"
                    + "where " + tipo + " date(venta.fecha)=CURDATE() and venta.activo = 1\n"
                    + "group by detalleventa.id_producto, detalleventa.preciovendido\n"
                    + "order by cantidad*(preciovendido-detalleventa.preciocompra) desc");

            rs = ps.executeQuery();
            rsm = (ResultSetMetaData) rs.getMetaData();
            ArrayList<Object[]> data = new ArrayList<>();
            while (rs.next()) {

                Object[] rows = new Object[jTable1.getColumnCount()];
                for (int i = 0; i < rows.length; i++) {
                    rows[i] = rs.getObject(i + 1);
                }
                data.add(rows);
                ps=(PreparedStatement)cn.prepareStatement("select sum(cantidad) from gastos where date(fecha)= CURDATE()");
                rs=ps.executeQuery();
                if(rs.next())
                gastos.setText(rs.getString(1));
            }
            for (int i = 0; i < data.size(); i++) {
                dtm.addRow(data.get(i));
            }
            

            sumarTodo();
        } catch (SQLException ex) {
            Logger.getLogger(ventasdia.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    private void sumarTodo() {
        double total = 0, tc = 0, tv = 0;
        for (int i = 0, rows = dtm.getRowCount(); i < rows; i++) {
            total += (Double.parseDouble(jTable1.getValueAt(i, 5).toString()));
            tv += (Double.parseDouble(jTable1.getValueAt(i, 4).toString()));
            tc += (Double.parseDouble(jTable1.getValueAt(i, 3).toString()));
        }
        compras.setText(nf.format(tc));
        ventas.setText(nf.format(tv));
        utilidad.setText(nf.format(total));
        jTable1.getColumnModel().getColumn(5).setCellRenderer(new DecimalFormatRenderer());
        jTable1.getColumnModel().getColumn(4).setCellRenderer(new DecimalFormatRenderer());
        jTable1.getColumnModel().getColumn(3).setCellRenderer(new DecimalFormatRenderer());
    }

    static class DecimalFormatRenderer extends DefaultTableCellRenderer {

        private static final NumberFormat formatter = NumberFormat.getCurrencyInstance(Locale.getDefault());

        public Component getTableCellRendererComponent(
                JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
            // First format the cell value as required

            value = formatter.format((Number) value);

            // And pass it on to parent class 

            return super.getTableCellRendererComponent(
                    table, value, isSelected, hasFocus, row, column);
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonGroup1 = new javax.swing.ButtonGroup();
        jPanel1 = new javax.swing.JPanel();
        jSpinField4 = new com.toedter.components.JSpinField();
        jSpinField2 = new com.toedter.components.JSpinField();
        jLabel6 = new javax.swing.JLabel();
        jDateChooser1 = new com.toedter.calendar.JDateChooser();
        jLabel1 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jSpinField1 = new com.toedter.components.JSpinField();
        jLabel8 = new javax.swing.JLabel();
        jDateChooser2 = new com.toedter.calendar.JDateChooser();
        jButton2 = new javax.swing.JButton();
        jSpinField6 = new com.toedter.components.JSpinField();
        jSpinField5 = new com.toedter.components.JSpinField();
        jLabel2 = new javax.swing.JLabel();
        jSpinField3 = new com.toedter.components.JSpinField();
        jLabel9 = new javax.swing.JLabel();
        exportar = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        formaPago = new javax.swing.JComboBox();
        jComboBox2 = new javax.swing.JComboBox();
        jLabel10 = new javax.swing.JLabel();
        jLabel12 = new javax.swing.JLabel();
        mostrarGastos = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jPanel2 = new javax.swing.JPanel();
        ventas = new javax.swing.JLabel();
        todo = new javax.swing.JRadioButton();
        cursos = new javax.swing.JRadioButton();
        jLabel13 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        productos = new javax.swing.JRadioButton();
        compras = new javax.swing.JLabel();
        jLabel11 = new javax.swing.JLabel();
        utilidad = new javax.swing.JLabel();
        jLabel14 = new javax.swing.JLabel();
        gastos = new javax.swing.JLabel();

        setClosable(true);
        setIconifiable(true);
        setMaximizable(true);
        setResizable(true);

        jLabel6.setText(":");

        jLabel1.setText("Hora inicio:");

        jLabel4.setText(":");

        jLabel5.setText("Hora Fin:");

        jLabel3.setText(":");

        jButton1.setText("MostrarVentas");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jLabel8.setText("Fecha Inicio");

        jButton2.setText("Cerrar");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jLabel2.setText(":");

        jLabel9.setText("Fecha Final");

        exportar.setText("Exportar");
        exportar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                exportarActionPerformed(evt);
            }
        });

        jButton3.setText("Reporte");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        formaPago.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Todas", "Efectivo", "Tarjeta Credito", "Transferencia", "Cheque", "Deposito", "Credito" }));

        jComboBox2.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Todas" }));

        jLabel10.setText("Sucursal:");

        jLabel12.setText("Forma de pago:");

        mostrarGastos.setText("Mostrar Gastos");
        mostrarGastos.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mostrarGastosActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(formaPago, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jComboBox2, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGap(36, 36, 36)
                                .addComponent(jLabel8))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGap(39, 39, 39)
                                .addComponent(jLabel9))
                            .addComponent(jLabel1)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGap(1, 1, 1)
                                .addComponent(jLabel5))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jSpinField4, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel4)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jSpinField5, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(4, 4, 4)
                                .addComponent(jLabel6)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jSpinField6, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(jDateChooser2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jDateChooser1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jSpinField1, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel2)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jSpinField2, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel3)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jSpinField3, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(exportar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jButton3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jLabel10)
                            .addComponent(jLabel12)
                            .addComponent(mostrarGastos, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel8)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jDateChooser1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(5, 5, 5)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel2)
                        .addComponent(jLabel3))
                    .addComponent(jSpinField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jSpinField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jSpinField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel9)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jDateChooser2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel5)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel4)
                        .addComponent(jLabel6))
                    .addComponent(jSpinField6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jSpinField4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jSpinField5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel12)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(formaPago, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel10)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jComboBox2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(mostrarGastos)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(exportar)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton2)
                .addContainerGap())
        );

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Codigo", "Nombre", "Cantidad", "PCompra", "PVenta", "Utilidad"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Object.class, java.lang.Object.class, java.lang.Integer.class, java.lang.Double.class, java.lang.Double.class, java.lang.Double.class
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }
        });
        jScrollPane1.setViewportView(jTable1);

        ventas.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        ventas.setText("----");

        buttonGroup1.add(todo);
        todo.setText("Todo");
        todo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                todoActionPerformed(evt);
            }
        });

        buttonGroup1.add(cursos);
        cursos.setText("Cursos");
        cursos.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cursosActionPerformed(evt);
            }
        });

        jLabel13.setText("Compras Total:");

        jLabel7.setText("Utilidad Total:");

        buttonGroup1.add(productos);
        productos.setText("Productos");
        productos.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                productosActionPerformed(evt);
            }
        });

        compras.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        compras.setText("-----");

        jLabel11.setText("Ventas Total:");

        utilidad.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        utilidad.setText("----");

        jLabel14.setText("Gastos Total:");

        gastos.setText("0.00");

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(compras, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(ventas, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(utilidad, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                .addComponent(jLabel7)
                                .addComponent(jLabel11)
                                .addComponent(jLabel13, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(productos, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(cursos)
                                .addComponent(todo))
                            .addComponent(jLabel14)
                            .addComponent(gastos))
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(todo)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(productos)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(cursos)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel7)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(utilidad)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel11)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(ventas)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel13)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(compras)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel14)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(gastos))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 475, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 461, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(0, 0, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void buscarFecha() {
        String hI = "00:00:00", hF = "00:00:00", tipo = "",pago="";
        java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd ");
        if(formaPago.getSelectedIndex()!=0)pago=" and tipopago = "+formaPago.getSelectedItem()+" and";
        if ((jDateChooser1.getDate() != null) && (jDateChooser2.getDate() != null)) {
            fI=sdf.format(jDateChooser1.getDate()) + hI;
            fF=sdf.format(jDateChooser2.getDate()) + hF ;
            try {
                if (cursos.isSelected()) {
                    tipo = "productos.tipo = 'Curso' and";
                }
                if (productos.isSelected()) {
                    tipo = "productos.tipo = 'Producto' and";
                }
                dtm.setRowCount(0);
                hI = String.valueOf(jSpinField1.getValue()) + ":" + String.valueOf(jSpinField2.getValue()) + ":" + String.valueOf(jSpinField3.getValue());
                hF = String.valueOf(jSpinField4.getValue()) + ":" + String.valueOf(jSpinField5.getValue()) + ":" + String.valueOf(jSpinField6.getValue());
                cn = local_connection.getconnect();
                ps = (PreparedStatement) cn.prepareStatement("select productos.id_producto, IF(productos.id_producto!=-2,nombre,(select nombre from otros where detalle_venta = idetalle)) AS nombre, sum(cantidad),sum(cantidad*detalleventa.preciocompra) ,\n"
                        + "sum(cantidad*preciovendido), sum(cantidad*(preciovendido-detalleventa.preciocompra))\n"
                        + " from detalleventa join venta on detalleventa.folio=venta.folio\n"
                        + "join productos on productos.id_producto=detalleventa.id_producto\n"
                        + "where " + tipo + "venta.activo = 1 and"+pago+" venta.fecha between \"" +fI+ "\" and \"" +fF+ "\"\n"
                        + "group by detalleventa.id_producto, detalleventa.preciovendido\n"
                        + "order by cantidad*(preciovendido-detalleventa.preciocompra) desc");

                rs = ps.executeQuery();
                rsm = (ResultSetMetaData) rs.getMetaData();
                ArrayList<Object[]> data = new ArrayList<>();
                while (rs.next()) {

                    Object[] rows = new Object[jTable1.getColumnCount()];
                    for (int i = 0; i < rows.length; i++) {
                        rows[i] = rs.getObject(i + 1);
                    }
                    data.add(rows);

                }
                for (int i = 0; i < data.size(); i++) {
                    dtm.addRow(data.get(i));
                }
ps=(PreparedStatement)cn.prepareStatement("select sum(cantidad) from gastos where fecha between '"+ fI +"' and '" + fF+"'" );
                rs=ps.executeQuery();
                if(rs.next())
                gastos.setText(rs.getString(1));
                sumarTodo();
            } catch (SQLException ex) {
                 Logger.getLogger(ventasdia.class.getName()).log(Level.SEVERE, null, ex);
            }
        } else {
            cargarDatos();
        }
    }
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        buscarFecha();
        // TODO add your handling code here:
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        this.dispose();
        // TODO add your handling code here:
    }//GEN-LAST:event_jButton2ActionPerformed

    private void productosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_productosActionPerformed
        buscarFecha();         // TODO add your handling code here:
    }//GEN-LAST:event_productosActionPerformed

    private void todoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_todoActionPerformed
        buscarFecha();        // TODO add your handling code here:
    }//GEN-LAST:event_todoActionPerformed

    private void cursosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cursosActionPerformed
        buscarFecha();         // TODO add your handling code here:
    }//GEN-LAST:event_cursosActionPerformed

    private void exportarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exportarActionPerformed


        final JFileChooser fileopen = new JFileChooser() {
            public void approveSelection() {
                File f = getSelectedFile();
                if (f.exists() && getDialogType() == SAVE_DIALOG) {
                    int result = JOptionPane.showConfirmDialog(this,
                            "Este archivo ya existe, ¿Quieres sobreescribirlo?", "Archivo Existente",
                            JOptionPane.YES_NO_CANCEL_OPTION);
                    switch (result) {
                        case JOptionPane.YES_OPTION:
                            super.approveSelection();
                            return;
                        case JOptionPane.CANCEL_OPTION:
                            cancelSelection();
                            return;
                        default:
                            return;
                    }
                }
                super.approveSelection();
            }
        };
        int ret = fileopen.showSaveDialog(null);
        if (ret == JFileChooser.APPROVE_OPTION) {
            File file = new File(fileopen.getSelectedFile() + ".xls");
            try {
                new FileWriter(file);
                new ExcelTableExporter(jTable1, file, "Corte").export();
            } catch (IOException ex) {
                JOptionPane.showMessageDialog(null, ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
            }
        }
        // TODO add your handling code here:
    }//GEN-LAST:event_exportarActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        String Fi, Ff,tipoa="Producto",tipob="Curso";
        if(cursos.isSelected()) tipoa="Curso";
        if(cursos.isSelected()) tipob="Producto";
        File file = null;
        java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd ");
        hI = String.valueOf(jSpinField1.getValue()) + ":" + String.valueOf(jSpinField2.getValue()) + ":" + String.valueOf(jSpinField3.getValue());
        hF = String.valueOf(jSpinField4.getValue()) + ":" + String.valueOf(jSpinField5.getValue()) + ":" + String.valueOf(jSpinField6.getValue());
        final JFileChooser fileopen = new JFileChooser() {
            public void approveSelection() {
                File f = getSelectedFile();
                if (f.exists() && getDialogType() == SAVE_DIALOG) {
                    int result = JOptionPane.showConfirmDialog(this,
                            "Este archivo ya existe, ¿Quieres sobreescribirlo?", "Archivo Existente",
                            JOptionPane.YES_NO_CANCEL_OPTION);
                    switch (result) {
                        case JOptionPane.YES_OPTION:
                            super.approveSelection();
                            return;
                        case JOptionPane.CANCEL_OPTION:
                            cancelSelection();
                            return;
                        default:
                            return;
                    }
                }
                super.approveSelection();
            }
        };
          int ret = fileopen.showSaveDialog(null);
        if (ret == JFileChooser.APPROVE_OPTION) {
            file = new File(fileopen.getSelectedFile() + ".pdf");
            }
        try {

            if ((jDateChooser1.getDate() != null) && (jDateChooser1.getDate() != null)) {
                Fi = sdf.format(jDateChooser1.getDate()) + hI;
                Ff = sdf.format(jDateChooser2.getDate()) + hF;
            } else {
                Fi = sdf.format(new Date())+ "00:00:00";
                Ff = sdf.format(new Date())+ "23:59:59";
            }

            URL resource = ventasdia.class.getResource("utilidadd.jasper");
            JasperReport reporte = (JasperReport) JRLoader.loadObject(resource);
            Map<String, Object> parametros = new HashMap<>();
            parametros.put("Fi", Fi);
            parametros.put("Ff", Ff);
            parametros.put("Ta", tipoa);
            parametros.put("Tb", tipob);
            JasperPrint jasperPrint = JasperFillManager.fillReport(reporte, parametros, cn);
            JRExporter exporter = new JRPdfExporter();
            exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
             new FileWriter(file);
            exporter.setParameter(JRExporterParameter.OUTPUT_FILE,file);
            exporter.exportReport();
            System.gc();
            // TODO add your handling code here:
        } catch (JRException | IOException ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_jButton3ActionPerformed

    private void mostrarGastosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mostrarGastosActionPerformed
         if(fI.equals(""))fI="CURDATE()";
         if(fF.equals(""))fF="CURDATE()";
        Gastos gastar = new Gastos(fI,fF);
        
            gastar.setVisible(true);
            Principal.estatico.add(gastar);
       
        
        // TODO add your handling code here:
    }//GEN-LAST:event_mostrarGastosActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.JLabel compras;
    private javax.swing.JRadioButton cursos;
    private javax.swing.JButton exportar;
    private javax.swing.JComboBox formaPago;
    private javax.swing.JLabel gastos;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JComboBox jComboBox2;
    private com.toedter.calendar.JDateChooser jDateChooser1;
    private com.toedter.calendar.JDateChooser jDateChooser2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel13;
    private javax.swing.JLabel jLabel14;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private com.toedter.components.JSpinField jSpinField1;
    private com.toedter.components.JSpinField jSpinField2;
    private com.toedter.components.JSpinField jSpinField3;
    private com.toedter.components.JSpinField jSpinField4;
    private com.toedter.components.JSpinField jSpinField5;
    private com.toedter.components.JSpinField jSpinField6;
    private javax.swing.JTable jTable1;
    private javax.swing.JButton mostrarGastos;
    private javax.swing.JRadioButton productos;
    private javax.swing.JRadioButton todo;
    private javax.swing.JLabel utilidad;
    private javax.swing.JLabel ventas;
    // End of variables declaration//GEN-END:variables
}
